﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace TushuGuan_GUI
{
    public class StudentList
    {
        const int banben = 1;
        public List<Student> Students { get; set; } = new List<Student>();

        public StudentList()
        {
            Load();
        }

        public List<BookBorrowedPlus> AllLendBooks()
        {
            List<BookBorrowedPlus> result = new List<BookBorrowedPlus>();
            //遍历学生列表
            foreach (Student student in Students)
            {
                foreach(var item in student.Lend)
                {
                    BookBorrowedPlus bookBorrowedPlus = new BookBorrowedPlus
                    {
                        StudentId = student.StudentID,
                        ISBN = item.ISBN,
                        Time = item.Time,
                        Lasttime = item.Lasttime
                    };
                    result.Add(bookBorrowedPlus);
                }
            }
            return result;
        }

        internal List<BookBorrowedPlus> AllOverdueLendBooks()
        {
            List<BookBorrowedPlus> result = new List<BookBorrowedPlus>();
            //遍历学生列表
            foreach (Student student in Students)
            {
                foreach (var item in student.Lend)
                {
                    if (item.Time.AddDays(item.Lasttime) < DateTime.Now)
                    {
                        BookBorrowedPlus bookBorrowedPlus = new BookBorrowedPlus
                        {
                            StudentId = student.StudentID,
                            ISBN = item.ISBN,
                            Time = item.Time,
                            Lasttime = item.Lasttime
                        };
                        result.Add(bookBorrowedPlus);
                    }
                    
                }
            }
            return result;
        }

        /// <summary>
        /// 添加学生
        /// </summary>
        /// <param name="studentId">学生ID</param>
        public void AddStudent(string studentId)
        {
            //新建学生
            Student student = new Student
            {
                StudentID = studentId
            };
            //添加学生到学生列表
            Students.Add(student);
            Save();

        }

        public void RemoveStudent(string studentId)
        {
            //遍历学生列表
            for (int i = 0; i < Students.Count; i++)
            {
                //判断是否匹配
                if (Students[i].StudentID == studentId)
                {
                    Students.RemoveAt(i);
                }
            }
            Save();

        }

        internal List<Student> SearchStudents(string studentId)
        {
            List<Student> result = new List<Student>();
            foreach (Student student in Students)
            {
                if (student.StudentID.IndexOf(studentId) > -1)
                {
                    result.Add(student);
                }
            }
            Save();

            return result;
        }

        internal bool RemoveStudents(List<int> studentsRemove)
        {
            bool if_success = true;
            List<string> studentIds = new List<string>();
            for (int i = 0; i < studentsRemove.Count; i++)
            {
                try
                {
                    studentIds.Add(Students[studentsRemove[i] - 1].StudentID);

                }
                catch
                {
                    if_success = false;
                }
            }
            for (int i = 0; i < studentIds.Count; i++)
            {
                try
                {
                    RemoveStudent(studentIds[i]);

                }
                catch
                {
                    if_success = false;
                }
            }
            Save();

            return if_success;
        }

        public void LendBook(string isbn, string studentId, int limited = 5)
        {
            Student student_ = null;
            for (int i = 0; i < Students.Count; i++)
            {
                if (Students[i].StudentID == studentId)
                {
                    student_ = Students[i];
                }
            }
            if (student_ == null)
            {
                throw new Exception("找不到此学生：" + studentId);
            }

            student_.LendBook(isbn, limited);
            Save();

        }
        public void ReturnBook(string isbn, string studentId)
        {
            Student student_ = null;
            for (int i = 0; i < Students.Count; i++)
            {
                if (Students[i].StudentID == studentId)
                {
                    student_ = Students[i];
                }
            }
            if (student_ == null)
            {
                throw new Exception("找不到此学生：" + studentId);
            }

            student_.ReturnBook(isbn);
            Save();

        }
        public void Save()
        {
            //序列化
            JObject data = new JObject(new JProperty("banben", banben));
            data.Add(new JProperty("Count", Students.Count));
            for (int i = 0; i < Students.Count; i++)
            {
                data.Add(new JProperty(i.ToString(), Students[i].Save()));
            }
            //保存
            //新建文件
            FileStream xiaFile = new FileStream("students.json", FileMode.Create);
            //写入
            byte[] buf = Encoding.UTF8.GetBytes(data.ToString());
            xiaFile.Write(buf, 0, buf.Length);
            xiaFile.Flush();
            xiaFile.Close();
        }
        public void Load()
        {
            try
            {
                //打开文件
                FileInfo fi = new FileInfo("students.json");
                long len = fi.Length;

                FileStream fs = new FileStream("students.json", FileMode.Open);
                byte[] buffer = new byte[len];
                fs.Read(buffer, 0, (int)len);//读取文件
                fs.Close();//关闭
                string str = Encoding.UTF8.GetString(buffer);//转码
                var json = (JObject)JsonConvert.DeserializeObject(str);
                switch (int.Parse(json["banben"].ToString()))
                {
                    case 1:
                        Load_1(str);
                        break;
                    default:
                        return;
                }
                if (int.Parse(json["banben"].ToString()) != banben)
                {
                    Save();
                }
            }
            catch
            {
                Save();
            }
        }

        public void Load_1(string data)
        {
            var json = (JObject)JsonConvert.DeserializeObject(data);
            var Count = json["Count"];
            int count_ = int.Parse(Count.ToString());

            Students.Clear();
            for (int i = 0; i < count_; i++)
            {
                var linshi = json[i.ToString()];
                Student student = new Student();
                student.Load(linshi.ToString());

                Students.Add(student);
            }
        }

    }
}
